package com.jasiri.project.ui.process.page

import android.content.Intent
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity
import com.jasiri.project.R
import com.jasiri.project.databinding.PageFaceBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.ui.process.activity.CameraFaceActivity
import com.jasiri.project.ui.process.activity.ProcessActivity
import com.jasiri.project.utils.dialog.PermissionReasonDialog
import com.jasiri.project.utils.dialog.SubmitSuccessDialog
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.gilde.ImageUtil
import com.jasiri.project.utils.helper.JasiriPermissionReasonHelper
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.log.HHLog
import com.jasiri.lib.permission.OnPermissionCallback
import com.jasiri.lib.permission.Permission
import com.jasiri.lib.permission.XXPermissions
import com.jasiri.lib.baseadapter.JasiriBaseAdapterUtil.getColor
import com.jasiri.project.app.App
import com.jasiri.project.lib.dev.JasiriSysDataHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/23 10:31
 * @Annotation：人脸识别
 */
class FacePage: ProFragment(), CoroutineScope by MainScope() {

    private var _binding: PageFaceBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    //是否选中删除信息,默认选中
    private var isSelectedDelete = true

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageFaceBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        isSelectedDelete = true
        showSelectedDeleteViewTips()
        showFaceBeforeView()
    }

    override fun initListener() {
        //切换是否选中删除个人信息
        _binding?.imgSelected?.setOnClickListener {
            isSelectedDelete = !isSelectedDelete
            showSelectedDeleteViewTips()
        }
        _binding?.imgView?.setOnClickListener {
            if (faceImgPath.isEmpty()){
                _binding?.btnSubmitAndStart?.callOnClick()
            }
        }
        //开始 、 提交
        _binding?.btnSubmitAndStart?.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                    addEvent(EventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                    faceCameraResultLauncher.launch(Intent(context,CameraFaceActivity::class.java))
                } else {
                    showSikadwaPermissionReasonDialog()
                }
                return@setOnClickListener
            }
            //提交
            val params = JSONObject().addCommonParams().apply {
                put("path", AppUrls.PATH.OCR_INFO)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_STEP_FACE_CONFIRM_SUBMIT,"")
            //上报位置和陀螺仪数据
            JasiriSysDataHelper.onCheckSubmitDataByTypes(App.instance(), arrayListOf("T11","T12"),"Selfie Page")

            //选中删除信息提示
            if (isSelectedDelete){
                showSelfieSubmitDeleteInformationTipsDialog(params)
            } else {
                val act = context as ProcessActivity
                act.submitAction(params)
            }
        }

        //删除
        _binding?.removeLayout?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_STEP_FACE_REMOVE_PHOTO,faceImgUrl)
            if (faceImgPath.isNotEmpty()){
                //删除图片
                val imgFile = File(faceImgPath)
                if (imgFile.isFile){
                    imgFile.delete()
                }
                faceImgPath = ""
            }
            faceImgUrl = ""
            showFaceBeforeView()
        }
    }

    override fun initData() {
        addEvent(EventType.PAGE.PAGE_STEP_FACE_START,"")

        val showApprovedKey1 = getString(R.string.process_face_submit_approved_tips_over)
        val showApprovedKey2 = getString(R.string.process_face_submit_approved_tips_days)
        val showApprovedText = String.format(getString(R.string.process_face_submit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textSelfieApproved?.text = approvedTipsSpannable
    }

    private fun showSelectedDeleteViewTips(){
        when(isSelectedDelete){
            true -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_selected)
            }
            else -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_normal)
            }
        }
    }

    /**
     * 显示权限说明
     */
    private fun showSikadwaPermissionReasonDialog(){
        val item = JasiriPermissionReasonHelper.gJasiriCameraItem()
        val requestPermission = item.optString("permission")
        val dialog = PermissionReasonDialog(requireContext(),requestPermission,object : PermissionReasonDialog.IDialogCallback{
            override fun onPermissionAgreeClick() {
                addEvent(EventType.CLICK.CLICK_PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                showSikadwaRequestSystemPermission()
            }
            override fun onPermissionDenyClick() {
                addEvent(EventType.CLICK.CLICK_PERMISSION_REASON_DIALOG_DENY,requestPermission)
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.showSikadwaPermissionReason(item)
    }

    /**
     * 申请系统权限
     */
    private fun showSikadwaRequestSystemPermission(){
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(Permission.CAMERA)
            .request(object:
                OnPermissionCallback {
                override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,
                        Permission.CAMERA)
                    addEvent(EventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                    faceCameraResultLauncher.launch(Intent(context,CameraFaceActivity::class.java))
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,
                        Permission.CAMERA)
                    XXPermissions.startPermissionActivity(requireContext(),permissions)
                }
            })
    }

    /**
     * 提交成功提示
     */
    private fun showSelfieSubmitDeleteInformationTipsDialog(params: JSONObject){
        val sendSuccessDialog = SubmitSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(false)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSubmitSuccess(getString(R.string.process_face_submit_success_tips))
        Handler(Looper.getMainLooper()).postDelayed({
            sendSuccessDialog.dismiss()
            val act = context as ProcessActivity
            act.submitAction(params)
        },1500)
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            FragmentActivity.RESULT_OK -> {
                result.data?.let {
                    faceImgPath = it.getStringExtra("imgLocalPath").toString()
                    faceImgUrl = it.getStringExtra("imgUrl").toString()
                    HHLog.e(">>>>>>>>>Face imgLocalPath：$faceImgPath")
                }
                showFaceAfterView()
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showFaceBeforeView(){
        _binding?.imgView?.setImageResource(R.mipmap.img_face_default_avater)
        _binding?.removeLayout?.visibility = View.INVISIBLE
        _binding?.btnSubmitAndStart?.text = getString(R.string.process_face_start)
    }

    /**
     * 显示拍照之后的View
     */
    private fun showFaceAfterView(){
        ImageUtil.instance?.loadImageUrl(context,_binding?.imgView,faceImgPath)
        _binding?.removeLayout?.visibility = View.VISIBLE
        _binding?.btnSubmitAndStart?.text = getString(R.string.process_face_submit)
    }


    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_STEP_FACE_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}